#!/bin/sh
# preinst script for salt-master.
#
# See: dh_installdeb(1).

set -e

# Summary of how this script can be called:
#        * <new-preinst> 'install'
#        * <new-preinst> 'install' <old-version>
#        * <new-preinst> 'upgrade' <old-version>
#        * <old-preinst> 'abort-upgrade' <new-version>
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package.

[ -n "$SALT_HOME" ] || SALT_HOME=/opt/saltstack/salt
[ -n "$SALT_USER" ] || SALT_USER=salt
[ -n "$SALT_NAME" ] || SALT_NAME="Salt"
[ -n "$SALT_GROUP" ] || SALT_GROUP=salt

case "$1" in
  install)
    ;;

  upgrade)
    . /usr/share/debconf/confmodule
    if [ -f /run/salt-master.pid ]
    then
        CUR_USER=$(ls -dl /run/salt-master.pid | cut -d ' ' -f 3)
        CUR_GROUP=$(ls -dl /run/salt-master.pid | cut -d ' ' -f 4)
    else
        CUR_USER=$SALT_USER
        CUR_GROUP=$SALT_GROUP
    fi
    db_set salt-master/user $CUR_USER
    chown -R $CUR_USER:$CUR_GROUP /etc/salt/pki/master /etc/salt/master.d \
                                  /var/log/salt/master /var/log/salt/key \
                                  /var/cache/salt/master /var/run/salt/master \
                                  || true

    if [ ! -f /var/lib/systemd/deb-systemd-helper-enabled/salt-master.service.dsh-also ]
    then
        # Workaround service status detection
        echo /etc/systemd/system/multi-user.target.wants/salt-master.service > /var/lib/systemd/deb-systemd-helper-enabled/salt-master.service.dsh-also
    fi
  ;;

  abort-upgrade)
  ;;

  *)
    echo "preinst called with unknown argument '$1'" >&2
    exit 1
  ;;
esac

# remove incorrectly installed ufw salt-master directory - issue 57712
test -d /etc/ufw/applications.d/salt-master && rm -rf /etc/ufw/applications.d/salt-master || /bin/true

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
